import React, { useRef, useState, useEffect } from "react";
import { Button } from "antd";
import { CustomerServiceOutlined } from "@ant-design/icons";

const DraggableButton = ({ onClick }) => {
  const buttonRef = useRef(null);
  const [position, setPosition] = useState({ x: window.innerWidth - 100, y: window.innerHeight - 140 });

  useEffect(() => {
    const handleMouseMove = (e) => {
      const newX = e.clientX;
      const newY = e.clientY;
      if (newX < 0 || newY < 0) {
        return;
      }
      setPosition({ x: newX, y: newY });
    };

    const handleMouseUp = () => {
      document.removeEventListener("mousemove", handleMouseMove);
      document.removeEventListener("mouseup", handleMouseUp);
    };

    if (buttonRef.current) {
      buttonRef.current.addEventListener("mousedown", () => {
        document.addEventListener("mousemove", handleMouseMove);
        document.addEventListener("mouseup", handleMouseUp);
      });
    }

    return () => {
      if (buttonRef.current) {
        buttonRef.current.removeEventListener("mousedown", () => {
          document.removeEventListener("mousemove", handleMouseMove);
          document.removeEventListener("mouseup", handleMouseUp);
        });
      }
    };
  }, []);

  return (
    <div
      style={{
        position: "fixed",
        zIndex:1000,
        transform: `translate(${position.x}px, ${position.y}px)`,
        transition: "0.2s",
      }}
    >
      <Button
        ref={buttonRef}
        shape="circle"
        type="primary"
        size="large"
        icon={<CustomerServiceOutlined />}
        onClick={onClick}
      ></Button>
    </div>
  );
};

export default DraggableButton;
